/* eslint-disable linebreak-style */
import React, { PureComponent } from 'react';
import { Card, Form, Col, Row, Popconfirm, DatePicker, Input, Select, message, Button } from 'antd';
import { routerRedux } from 'dva/router';
import PropTypes from 'prop-types';
import router from 'umi/router';
import moment from 'moment';
import { connect } from 'dva';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import FooterToolbar from '@/components/FooterToolbar/index';
import styles from './style.less';
import { getDictOptionsByCode, findDicByCode } from '@/support/common';

const { Option } = Select;

const fieldLabels = {
  vin: 'VIN',
  brandId: '品牌',
  styleId: '车型',
  seriesId: '车系',
  status: '车辆状态',
  licence: '车牌',
  colorId: '颜色',
  doptCode: '发动机号',
  dealerId: '经销商',
  assType: 'assType',
  pin: '安全码',
  pinValidDate: '安全码有效时间',
  language: '车机语言',
  enrollStatus: '激活状态',
  produceDate: '生产日期',
  publishDate: '发布日期',
  realVin: '真实VIN',
  vhlType: '车辆类型',
  remarks: '备注',
};


@connect(state => ({
  vehicle: state.vehicle,
  currentUser: state.user.currentUser,
  basedata: state.basedata,
}))
// @Form.create()
export default class VehicleEdit extends PureComponent {
  static contextTypes = {
    dicData: PropTypes.any,
  };
  state = {
    seriesOptions: [],
    typeOptions: [],
    colorOptions: [],
    dealerOptions: [],
    query: '',
    buttonLoading: false,
    brandOptions: [],
  };
  UNSAFE_componentWillMount() {
    if (this.props.location && this.props.location.state) {
      this.setState({
        query: this.props.location.state.obj,
      });
    }
    const record = this.props.location.state?.data;
    console.log('record', record)
    this.props.dispatch({
      type: 'basedata/brandFetch',
      callback: (res) => {
        this.setState({ 
           brandOptions: res?.data?.map((item)=>{
            return {
              label: item.brandName,
              value: item.brandCode
            }
          }),
          });
        }
    });
    this.props.dispatch({
      type: 'basedata/colorList',
      callback: (response) => {
        this.setState({
          colorOptions: response.filter(item => item.code !== '').map(d => <Option key={d.code}>{d.name}</Option>),
        });
      },
    });
    console.log('xxxxxxx')
    console.log('this.props.location.state', this.props.location.state)
    if (this.props.location.state) {
      const record = this.props.location.state.data;
      console.log('record.brandId', record.brandId)
      console.log('record.seriesId', record.seriesId)
      if (record.brandId) {
        this.props.dispatch({
          type: 'basedata/seriesList',
          payload: { brandId: record.brandId },
          callback: (response) => {
            if (response) {
              this.setState({
                seriesOptions: response.filter(item => item.code !== '').map(d => <Option key={d.code}>{d.name}</Option>),
              });
            } else {
              this.setState({
                seriesOptions: '',
                typeOptions: '',
              });
            }
          },
        });
      //    //根据品牌查询项目
      // this.props.dispatch({
      //   type: 'basedata/findProjectIdsByBrandCode',
      //   payload: { brandCode : record.brandId },
      //   callback: (response) => {
      //     if (response) {
      //       this.setState({
      //         projectOptions: response.data.filter(item => item.brandCode === value).map(d => <Option key={d.projectId}>{d.projectName}</Option>),
      //       });
      //     } else {
      //       this.setState({
      //         projectOptions: '',
      //       });
      //     }
      //   },
      // });
      //根据品牌查询经销商
      this.props.dispatch({
        type: 'basedata/findDealerByBrandCode',
        payload: { brandCode : record.brandId },
        callback: (response) => {
          if (response) {
            console.log('dealerrrrrr', response)
            this.setState({
              dealerOptions: response.data.map(d => <Option key={d.code}>{d.name}</Option>),
            });
          } else {
            this.setState({
              dealerOptions: '',
            });
          }
        },
      });
      }

      if (record.seriesId) {
        this.props.dispatch({
          type: 'basedata/typeList',
          payload: { seriesId: record.seriesId },
          callback: (response) => {
            if (response) {
              this.setState({
                typeOptions: response.filter(item => item.code !== '').map(d => <Option key={d.code}>{d.name}</Option>),
              });
            } else {
              this.setState({
                typeOptions: '',
              });
            }
          },
        });
      }
    }
  }
  componentDidMount() {
    if (this.props.location.state) {
      const record = this.props.location.state.data;
      this.refs.form.setFieldsValue({
        vin: record.vin,
        brandId: record.brandId,
        styleId: record.styleId,
        seriesId: record.seriesId,
        status: record.status === null ? record.status : record.status.toString(),
        licence: record.licence,
        colorId: record.colorId,
        doptCode: record.doptCode,
        insuranceId: record.insuranceId,
        dealerId: record.dealerId,
        assType: record.assType === null ?
          record.assType : record.assType.toString(),
        pin: record.pin,
        pinValidDate: record.pinValidDate ? moment(record.pinValidDate) : record.pinValidDate,
        language: record.language,
        factory: record.factory,
        enrollStatus: record.enrollStatus === null ?
          record.enrollStatus : record.enrollStatus.toString(),
        insuranceDate: record.insuranceDate ? moment(record.insuranceDate) : record.insuranceDate,
        insuranceStatus: record.insuranceStatus,
        unenrollDate: record.unenrollDate ? moment(record.unenrollDate) : record.unenrollDate,
        buyDate: record.buyDate ? moment(record.buyDate) : record.buyDate,
        produceDate: record.produceDate ? moment(record.produceDate) : record.produceDate,
        publishDate: record.publishDate ? moment(record.publishDate) : record.publishDate,
        purchaseDate: record.purchaseDate ? moment(record.purchaseDate) : record.purchaseDate,
        realVin: record.realVin,
        remarks: record.remarks,
        sid: record.sid,
        createDate: record.createDate ? moment(record.createDate) : record.createDate,
        createBy: record.createBy,
        delFlag: record.delFlag,
        version: record.version,
        realNameStatus: record.realNameStatus,
        mnoSyncStatus: record.mnoSyncStatus,
        vhlType: record.vhlType,
        groupId: record.groupId,
        enrollDate: record.enrollDate ? moment(record.enrollDate) : record.enrollDate,
        sapDate: record.sapDate ? moment(record.sapDate) : record.sapDate,
        availableDate: record.availableDate ? moment(record.availableDate) : record.availableDate,
      });
    }
  }

  onBrandSelect = (value) => {
    this.refs.form.setFieldsValue({ seriesId: '', styleId: '', projectId: '', dealerId: ''});
    if (value) {
      this.props.dispatch({
        type: 'basedata/seriesList',
        payload: { brandId: value },
        callback: (response) => {
          if (response) {
            this.setState({
              seriesOptions: response.filter(item => item.code !== '').map(d => <Option key={d.code}>{d.name}</Option>),
            });
          } else {
            this.setState({
              seriesOptions: '',
              typeOptions: '',
            });
          }
        },
      });
      // //根据品牌查询项目
      // this.props.dispatch({
      //   type: 'basedata/findProjectIdsByBrandCode',
      //   payload: { brandCode : value },
      //   callback: (response) => {
      //     if (response) {
      //       this.setState({
      //         projectOptions: response.data.filter(item => item.brandCode === value).map(d => <Option key={d.projectId}>{d.projectName}</Option>),
      //       });
      //     } else {
      //       this.setState({
      //         projectOptions: '',
      //       });
      //     }
      //   },
      // });
      //根据品牌查询经销商
      this.props.dispatch({
        type: 'basedata/findDealerByBrandCode',
        payload: { brandCode : value },
        callback: (response) => {
          if (response) {
            this.setState({
              dealerOptions: response.data.filter(item => item.brandId === value).map(d => <Option key={d.code}>{d.name}</Option>),
            });
          } else {
            this.setState({
              dealerOptions: '',
            });
          }
        },
      });
    } else {
      this.setState({
        seriesOptions: '',
        typeOptions: '',
        // projectOptions: '',
        dealerOptions: ''
      });
    }
  }

  onSerieSelect = (value) => {
    this.refs.form.setFieldsValue({ styleId: '' });
    if (value) {
      this.props.dispatch({
        type: 'basedata/typeList',
        payload: { seriesId: value },
        callback: (response) => {
          if (response) {
            this.setState({
              typeOptions: response.filter(item => item.code !== '').map(d => <Option key={d.code}>{d.name}</Option>),
            });
          } else {
            this.setState({
              typeOptions: '',
            });
          }
        },
      });
    } else {
      this.setState({
        typeOptions: '',
      });
    }
  }

  goBack = () => {
    const { query } = this.state;
    const { dispatch } = this.props;
    dispatch(routerRedux.push({ pathname: '/deviceManager/vehicle', state: { query } }));
  }

  ok = (values) => {
    this.setState({
      buttonLoading: true,
    });
    const { query } = this.state;
    this.props.dispatch({
      type: 'vehicle/edit',
      payload: values,
      callback: (response) => {
        if (response.statusCode === '0') {
          message.success('操作成功');
          this.refs.form.resetFields();
          this.props.dispatch(routerRedux.push({ pathname: '/deviceManager/vehicle', state: { query } }));
        } else {
          message.error(response.statusMessage);
        }
        this.setState({
          buttonLoading: false,
        });
      },
    });
  }

  render() {
    const { seriesOptions,
      typeOptions, colorOptions, dealerOptions,
      buttonLoading, brandOptions } = this.state;
    const { brandCodes } = this.props.currentUser;
    const statusOptions = getDictOptionsByCode(this.context.dicData, 'vehicleStatus');
    const enrollStatusOptions = getDictOptionsByCode(this.context.dicData, 'vehicleEnrollStatus');
    const assTypeOptions = getDictOptionsByCode(this.context.dicData, 'vehicleAssType');

    // const { form, dispatch } = this.props;
    if (this.props.location.flag) {
      return (
        <PageHeaderLayout
          title=""
          wrapperClassName={styles.advancedForm}
        >
          <Card title="" className={styles.card} bordered={false}>
            <Form layout="vertical" ref="form" onFinish={this.ok}>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.brandId} name="brandId" rules={[{ required: true, message: '请选择品牌' }]} >
                    <Select disabled allowClear placeholder="请选择" onChange={this.onBrandSelect} getPopupContainer={triggerNode => triggerNode.parentNode} options={brandOptions} />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.seriesId} name="seriesId" rules={[{ required: false, message: '请输入车系' }]} >
                    <Select allowClear placeholder="请选择" onChange={this.onSerieSelect} getPopupContainer={triggerNode => triggerNode.parentNode}>
                      {seriesOptions}
                    </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.styleId} name="styleId" rules={[{ required: false, message: '请选择车型' }]} >
                    <Select allowClear placeholder="请选择" getPopupContainer={triggerNode => triggerNode.parentNode}>
                      {typeOptions}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.vin} name="vin" rules={[{ required: true, message: '请输入VIN' }]}>
                    <Input disabled maxLength="20" placeholder="请输入VIN" />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.status} name="status" rules={[{ required: true, message: '请选择车辆状态' }]}>
                    <Select allowClear placeholder="请选择" getPopupContainer={triggerNode => triggerNode.parentNode} options={statusOptions} />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.enrollStatus} name="enrollStatus" rules={[{ required: true, message: '请选择激活状态' }]}>
                    <Select disabled allowClear placeholder="请选择" getPopupContainer={triggerNode => triggerNode.parentNode} options={enrollStatusOptions} />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.licence} name="licence" rules={[{ required: false, message: '请输入车牌' }]}>
                    <Input maxLength="10" placeholder="请输入车牌" />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.colorId} name="colorId" rules={[{ required: false, message: '请选择颜色' }]}>
                    <Select allowClear placeholder="请选择" getPopupContainer={triggerNode => triggerNode.parentNode}>
                      {colorOptions}
                    </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.doptCode} name="doptCode" rules={[{ required: false, message: '请输入发动机号' }]}>
                    <Input maxLength="17" placeholder="请输入发动机号" />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.assType} name="assType" rules={[{ required: false, message: '请选择' }]}>
                    <Select allowClear placeholder="请选择" getPopupContainer={triggerNode => triggerNode.parentNode} options={assTypeOptions} />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.dealerId} name="dealerId" rules={[{ required: false, message: '请选择经销商' }]}>
                    <Select
                      allowClear
                      placeholder="请选择"
                      showSearch
                      getPopupContainer={triggerNode => triggerNode.parentNode}
                      optionFilterProp="children"
                    >
                      {dealerOptions}
                    </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.realVin} name="realVin" rules={[{ required: false, message: '请输入真实VIN' }]}>
                    <Input maxLength="20" placeholder="请输入真实VIN" />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.pin} name="pin" rules={[{ required: false, message: '请输入安全码' }]}>
                    <Input maxLength="32" placeholder="请输入安全码" />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.pinValidDate} name="pinValidDate" rules={[{ required: false, message: '请输入安全码有效时间' }]}>
                    <DatePicker
                      style={{ width: '100%' }}
                      placeholder="请输入安全码有效时间"
                      showTime
                      format="YYYY-MM-DD HH:mm:ss"
                    />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.language} name="language" rules={[{ required: false, message: '请输入车机语言' }]}>
                    <Input maxLength="5" placeholder="请输入车机语言" />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.produceDate} name="produceDate" rules={[{ required: false, message: '请输入生产日期' }]}>
                    <DatePicker
                      style={{ width: '100%' }}
                      placeholder="请输入生产日期"
                      showTime
                      format="YYYY-MM-DD HH:mm:ss"
                    />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.publishDate} name="publishDate" rules={[{ required: false, message: '请输入发布日期' }]}>
                    <DatePicker
                      style={{ width: '100%' }}
                      placeholder="请输入发布日期"
                      format="YYYY-MM-DD"
                    />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.remarks} name="remarks" rules={[{ required: false, message: '请输入备注' }]}>
                    <Input placeholder="请输入备注" />
                  </Form.Item>
                </Col>
              </Row>
              <Form.Item style={{ display: 'none' }} name="sid" rules={[{ required: false, message: '' }]}>
                <Input placeholder="" />
              </Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="createDate" >
                <DatePicker
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                />
              </Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="createBy"><Input /></Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="version"><Input /></Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="delFlag"><Input /></Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="realNameStatus"><Input /></Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="mnoSyncStatus"><Input /></Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="vhlType"><Input /></Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="groupId"><Input /></Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="insuranceId"><Input /></Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="factory"><Input /></Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="insuranceStatus"><Input /></Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name=""><Input /></Form.Item>

              <Form.Item style={{ display: 'none' }} label="" name="enrollDate">
                <DatePicker
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                />
              </Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="sapDate">
                <DatePicker
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                />
              </Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="availableDate">
                <DatePicker
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                />
              </Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="insuranceDate">
                <DatePicker
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                />
              </Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="unenrollDate">
                <DatePicker
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                />
              </Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="buyDate">
                <DatePicker
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                />
              </Form.Item>
              <Form.Item style={{ display: 'none' }} label="" name="purchaseDate">
                <DatePicker
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                />
              </Form.Item>
            </Form>
            <Form layout="vertical" hideRequiredMark>
              <Row gutter={16}>
                <Col xl={{ span: 5, offset: 9 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <div >
                    <Button loading={buttonLoading} key="submit" type="primary" size="default" onClick={() => this.refs.form.submit()}>
                      提交
                    </Button>
                    &nbsp;&nbsp;
                    <Popconfirm title="确定放弃修改吗?" onConfirm={this.goBack}>
                      <Button key="back" size="default">
                        取消
                      </Button>
                    </Popconfirm>
                  </div>
                </Col>
              </Row>
            </Form>
          </Card>
          <FooterToolbar />
        </PageHeaderLayout>
      );
    } else {
      return (
        <PageHeaderLayout
          title=""
        >
          <div align="center" width="100%" height="100%" style={{ marginTop: '250px' }}>
            <h2>未选择任何车辆,请返回列表选择车辆</h2>
            <a onClick={this.goBack}>返回</a>
          </div>
        </PageHeaderLayout>
      );
    }
  }
}
